package com.hm.health.BLE;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.ArrayMap;

import androidx.annotation.Nullable;

import java.util.Map;

/**
 * 标准心率设备，例如Polar，Jabra
 *
 * @author chenshi
 * @date 2017 /3/17
 */
public class StandardHeartRateDevice extends Service
        implements IBLEDevice {

    private ArrayMap<String, HrsDevice> mHrsDeviceMap = new ArrayMap<>();
    private Context mContext;
    private OnDeviceStatus mOnDeviceStatus;
    private ServiceBinder mServiceBinder;


    /**
     * Instantiates a new Standard heart rate device.
     */
    public StandardHeartRateDevice() {
        mContext = this;
        mServiceBinder = new ServiceBinder();
    }

    @Override
    public void connect(String strAddress) {
        if (mHrsDeviceMap.containsKey(strAddress)) {
            return;
        }

        HrsDevice hrsDevice = new HrsDevice(mContext);
        hrsDevice.setOnDeviceStatus(mOnDeviceStatus);
        mHrsDeviceMap.put(strAddress, hrsDevice);
        hrsDevice.connect(strAddress);
    }

    @Override
    public void setOnDeviceStatus(OnDeviceStatus onDeviceStatus) {
        mOnDeviceStatus = onDeviceStatus;
        for (Map.Entry<String, HrsDevice> device : mHrsDeviceMap.entrySet()) {
            device.getValue().setOnDeviceStatus(onDeviceStatus);
        }
    }

    @Override
    public Map<String, Boolean> getDeviceStatusMap() {
        Map<String, Boolean> stateMap = new ArrayMap<>();
        for (Map.Entry<String, HrsDevice> deviceEntry : mHrsDeviceMap.entrySet()) {
            stateMap.put(deviceEntry.getKey(), deviceEntry.getValue().isConnected());
        }
        return stateMap;
    }

    @Override
    public void disconnect() {
        for (Map.Entry<String, HrsDevice> deviceEntry : mHrsDeviceMap.entrySet()) {
            deviceEntry.getValue().disconnect();
        }
        mHrsDeviceMap.clear();
    }

    @Override
    public void disconnect(String address) {
        if (mHrsDeviceMap.containsKey(address)) {
            mHrsDeviceMap.get(address).disconnect();
            mHrsDeviceMap.remove(address);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return  mServiceBinder;
    }

    public class ServiceBinder extends Binder {
        public StandardHeartRateDevice getService() {
            return StandardHeartRateDevice.this;
        }
    }
}
